export function hashCode(s) {
  if (!s) {
    return 0
  }
  let h = 0
  for (let i = 0; i < s.length; i++) {
    h = 31 * h + s.charCodeAt(i)
  }
  return h
}

export const
  reMobile = new RegExp('^(?<countryCode>[+][0-9]{1,2})?(?<phoneNumber>1[3456789]\\d{9})$'),
  reEmail = new RegExp('^(?<localPart>[A-Za-z0-9._%+-]+)@(?<domain>[A-Za-z0-9.-]+[.][A-Za-z]{2,})$'),
  reIdNumber = new RegExp('^(?<districtCode>[0-9]{6})(?<birthday>[0-9]{8})(?<sequence>[0-9]{3})(?<checkCode>[0-9Xx])$')

// 给敏感信息加星号
export function mask(s) {
  let r
  if (s === null) {
    return null
  }
  if (s === undefined) {
    return null
  }
  if (typeof s !== 'string'){
    return s
  }

  s = s.replace(/\s*/g, '')
  if ((r = reMobile.exec(s))) {
    const { groups: { phoneNumber } } = r
    return `${phoneNumber.substring(0, 3)}****${phoneNumber.substring(7)}`
  } else if ((r = reEmail.exec(s))) {
    const { groups: { localPart, domain } } = r
    return `${localPart.substring(0, 3)}*****@${domain}`
  } else if ((r = reIdNumber.exec(s))) {
    const { groups: { districtCode, sequence, checkCode } } = r
    return `${districtCode}********${sequence}${checkCode}`
  } else if (s.length > 6) {
    let startNumber = s.substring(0, 3)
    let endNumber = s.substring(s.length - 3, s.length)
    return `${startNumber}****${endNumber}`
  } else {
    return s
  }
}

// generate a version 4 (random) UUID
export function uuid() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    const n = Math.random() * 16 | 0
    const v = c === 'x' ? n : (n & 0x3 | 0x8)
    return v.toString(16)
  })
}

export function formatFileSize(bytes, decimalPoint = 2) {
  if (bytes || bytes === 0) {
    if (bytes === 0) return '0 Bytes'
    let k = 1000,
      sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
      i = Math.floor(Math.log(bytes) / Math.log(k))
    return (
      parseFloat((bytes / Math.pow(k, i)).toFixed(decimalPoint)) + ' ' + sizes[i]
    )
  }
  return ''
}

export function removeHtmlStyle(html) {
  const relStyle = /style\s*?=\s*?(['"])[\s\S]*?\1/g
  const relTag = /<.+?>/g
  const relClass = /class\s*?=\s*?(['"])[\s\S]*?\1/g
  let newHtml = ''
  if (html) {
    newHtml = html.replace(relStyle, '')
    newHtml = newHtml.replace(relTag, '')
    newHtml = newHtml.replace(relClass, '')
  }
  return newHtml
}

export function escapeStringForJS(str) {
  return JSON.stringify(str).slice(1, -1);
}
